// 云函数入口文件
const cloud = require('wx-server-sdk')
const TcbRouter = require('tcb-router');
cloud.init({
  // API 调用都保持和云函数当前所在环境一致
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const app = new TcbRouter({
    event
  })
  const collection = "user" //数据库的名称

  app.use(async (ctx, next) => {
    ctx.data = {}
    await next();
  });
  

  app.router('checkUser', async (ctx, next) => {
    ctx.body = await db.collection(collection).where({
      _openid: wxContext.OPENID // 填入当前用户 openid
    }).get()
  })

  app.router('addUser', async (ctx, next) => {
    ctx.body = await db.collection(collection)
      .add({
        data: {
          _openid: wxContext.OPENID,
          ...event.data
        }
      })
  })

  app.router('updateUser', async (ctx, next) => {
    ctx.body = await db.collection(collection).where({
      _openid: wxContext.OPENID
    }).update({
      data: {
        uid: event.uid
      },
    })
  })

  return app.serve();
}